﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour {
    Spaceship spaceship;

    // 血量
    public int hp = 1;

    // 分数
    public int point = 10;

    /// <summary>
    /// 控制能否开火的flag
    /// </summary>
    public bool isCanShot = false;

    // void Start()
    // {
    //     // 取得Spaceship
    //     spaceship = GetComponent<Spaceship> ();

    //     // 相对方向是Y轴负数的方向
    //     spaceship.Move (transform.up * -1);
    // }

    /// <summary>
    /// 初始化脚本改造成协程
    /// </summary>
    /// <returns>空</returns>
    IEnumerator Start () {

        spaceship = GetComponent<Spaceship> ();

        Move (transform.up * -1);

        if (!isCanShot) {

            yield break;
        }

        while (true) {

            // 取得全部的子要素
            for (int i = 0; i < transform.childCount; i++) {

                Transform shotPosition = transform.GetChild (i);

                // 根据ShotPosition的位置进行开火，攻击
                spaceship.Shot (shotPosition);
            }

            // 等待shotDelay秒
            yield return new WaitForSeconds (spaceship.shotDelay);
        }
    }

    // 机体的移动
    public void Move (Vector2 direction) {
        GetComponent<Rigidbody2D> ().velocity = direction * spaceship.speed;
    }

    void OnTriggerEnter2D (Collider2D other) {

        // 碰撞进入的对象是销毁区域的话 不要执行后续的动作
        var layerName = LayerMask.LayerToName (other.gameObject.layer);

        if (LayerMask.LayerToName (other.gameObject.layer) == "DestroyArea") {
            return;
        }

        // 把碰到的敌人子弹销毁掉
        Destroy (other.gameObject);

        if (layerName != "Bullet(Player)") {
            return;
        }

        hp -= other.GetComponent<Bullet> ().power;

        if (hp > 0) {
            // 触发变红的动画
            Debug.Log("Damege");
            spaceship.GetAnimator ().SetTrigger ("Damege");
            return;
        }

        FindObjectOfType<Score>().AddPoint(point);

        // 播放爆炸动画
        spaceship.PlayExplosion ();

        // 销毁自己（被打死了）
        Destroy (gameObject);
    }
}